package byx.container.annotation.extension.impl;

import byx.container.annotation.annotation.Init;
import byx.container.annotation.annotation.Order;
import byx.container.annotation.extension.core.ClassPostProcessor;
import byx.container.annotation.extension.core.ClassPostProcessorContext;
import byx.container.annotation.util.OrderUtils;
import byx.container.core.ObjectFactory;
import byx.container.core.RegisterInfo;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 处理Init注解
 */
@Order(Integer.MIN_VALUE)
public class InitProcessor implements ClassPostProcessor {
    private final ParameterResolver parameterResolver;

    public InitProcessor(ParameterResolver parameterResolver) {
        this.parameterResolver = parameterResolver;
    }

    @Override
    public ObjectFactory<?> postProcess(ClassPostProcessorContext ctx) {
        RegisterInfo registerInfo = ctx.getRegisterInfo();
        Class<?> type = registerInfo.getType();
        ObjectFactory<?> factory = registerInfo.getFactory();

        List<Method> methods = Arrays.stream(type.getMethods())
                .filter(m -> m.isAnnotationPresent(Init.class))
                .sorted(OrderUtils.comparator())
                .collect(Collectors.toList());

        for (Method m : methods) {
            ObjectFactory<?>[] params = parameterResolver.getParamFactories(m);
            factory = factory.invoke(m.getName(), params);
        }

        return factory;
    }
}
